
from rest_framework import serializers
from users.models import User
from django.contrib.auth.models import Group
from django.contrib.auth.hashers import make_password

class AdminGroupModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = Group
        fields = [
            'id',
            'name'
        ]


class AdminUserModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = [
            'id',
            'username',
            'email',
            'mobile',

            'password',
            'groups',
            'user_permissions'
        ]
        extra_kwargs = {
            'password': {'write_only': True}
        }

    def validate(self, attrs):
        """
        目的：在校验的过程中，直接加密密码，以及手动添加is_staff=True参数 --> 不管后续是新建还是更新，密码都加密了，is_staff=True；
        """
        # attrs = {"password": "12345678"......}
        # (1)、密码加密
        password = attrs.get('password') # 明文密码
        # attrs['password'] = 密文密码
        attrs['password'] = make_password(password) # 把attrs字典中的password键重新赋值为密文密码
        # (2)、有效数据手动添加is_staff=True
        attrs['is_staff'] = True
        return attrs # {"password": "pbkdf2_sha256$150000$y8aPO=...", "is_staff": True}







